package service

import (
	"errors"
	cQuery "ssadmin/common/query"
	"ssadmin/internal/admin/models"
	"ssadmin/internal/admin/models/command"
	"ssadmin/internal/admin/models/query"
	"strings"

	"gitee.com/sansaniot/ssiot-core/httpmvc/service"
)

type Role struct {
	roleModel *models.Role
	service.Service
}

func (r *Role) SetRoleModel(m *models.Role) {
	r.roleModel = m
}

func (e *Role) GetMenuIdList(d *query.RoleGetReq, menuIdList *[]string) error {
	var menuList []models.RoleMenu

	roleModel := models.Role{}
	if err := roleModel.FindRoleMenuList(e.Orm, &menuList, "role_id = ?", d.GetRoleId()); err != nil {
		return err
	}
	for _, menu := range menuList {
		*menuIdList = append(*menuIdList, menu.MenuId)
	}
	return nil
}

// Insert 创建Role对象
func (e *Role) Insert(c *command.RoleInsertReq) error {
	data := models.Role{}
	c.Generate(&data)
	if err := e.roleModel.Add(&data); err != nil {
		return err
	}

	//关联数据管理
	e.setRoleMenu(false,
		&command.RoleMenu{
			RoleId: data.RoleId,
			MenuId: c.MenuId,
		},
		c.SystemId,
	)
	return nil
}

// Update 修改Role对象
func (e *Role) Update(c *command.RoleUpdateReq) error {
	data := models.Role{}
	id := query.RoleQuery{RoleId: c.RoleId}
	where := cQuery.MakeCondition(id)
	err := e.Orm.Model(&models.Role{}).Scopes(where).First(&data).Error

	if err != nil {
		return err
	}

	c.Generate(&data)
	if err = data.Mod(e.Orm, &data, where); err != nil {
		return err
	}

	//关联数据管理
	e.setRoleMenu(true,
		&command.RoleMenu{
			RoleId: data.RoleId,
			MenuId: c.MenuIds,
		},
		c.SystemId,
	)

	return nil
}

func (e *Role) setRoleMenu(update bool, c *command.RoleMenu, systemId string) {
	ud := models.RoleMenu{}
	if update == true {
		//获取系统菜单
		mm := models.Menu{}
		menuList := make([]models.Menu, 0)
		_ = mm.FindListByConds(e.Orm, &menuList, "enable=?", "1")

		//删除角色当前系统菜单（角色有多系统菜单）
		if len(menuList) > 0 {
			delMenuIdList := make([]string, 0)
			for _, m := range menuList {
				delMenuIdList = append(delMenuIdList, m.MenuId)
			}
			//删除关联数据
			e.Orm.Model(ud).Where("role_id in (?) and menu_id in(?)", c.RoleId, delMenuIdList).Delete(ud)
		}
	}

	//插入关联数据
	menuRoleList := make([]models.RoleMenu, 0)
	menuIds := strings.Split(c.MenuId, ",")
	for _, id := range menuIds {
		menuRoleList = append(menuRoleList, models.RoleMenu{
			RoleId:        c.RoleId,
			MenuId:        id,
			DefaultStatus: "1",
		})
	}
	e.Orm.Model(ud).Create(&menuRoleList)
}

// Remove 删除Role
func (e *Role) Remove(d *command.RoleDeleteReq) error {
	data := models.Role{}
	con1 := "role_id in (?)"

	var userCount int64
	if err := data.FindUserCount(e.Orm, &userCount, con1, d.GetId()); err != nil {
		return err
	}

	if userCount > 0 {
		return errors.New("当前角色有用户使用，无法删除")
	}

	con2 := "id in (?)"
	if err := data.Del(e.Orm, con2, d.GetId()); err != nil {
		return err
	}
	//删除关联菜单
	if err := data.DelMenu(e.Orm, con1, d.GetId()); err != nil {
		return err
	}

	return nil
}
